package com.century.sjt.activity.wallet;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.entity.BankCard;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author:周玲波
 * @Description:添加银行卡
 * @date : 2016/8/17 19:06
 */
public class AddBankActivity extends BaseActivity {
    @BindView(R.id.add_bank_titlebar)
    SjtTitleBar titleBar;
    @BindView(R.id.et_username)
    EditText et_username;
    @BindView(R.id.et_idcard)
    EditText et_idcard;
    @BindView(R.id.et_bankcardno)
    EditText et_bankcardno;
    @BindView(R.id.btn_second)
    Button btn_second;
    private RequestQueue mQueue;
    private String userId,idCard,name,isRealName;
    private String phone,bankCardNo,bankCode,bankName,bankType,status;
    private  String Type = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sjt_add_bankcad_activity);
        ButterKnife.bind(this);
        mQueue = Volley.newRequestQueue(this);

        Intent intent =getIntent();
        Type=intent.getStringExtra("type");
        if (Type==null||Type.equals("")){
            Type="3";
        }
        Bundle bundle =getIntent().getExtras();
        if(bundle!=null){
            phone = bundle.getString("phone");
            if ("6".equals(Type)){
//                aMerchant=(MerchantList)getIntent().getSerializableExtra("Merchant");
            }
            bankCardNo = bundle.getString("bankCardNo");
            bankCode = bundle.getString("bankCode");
            bankName = bundle.getString("bankName");
            bankType = bundle.getString("bankType");
            status = bundle.getString("status");
        }
        initEvent();
        initView();
        initData();
    }

    @Override
    protected void initView() {
        titleBar.setTitle(getResources().getString(R.string.text_bind_bank_card));
        titleBar.setLeftIconResource(getResources().getString(R.string.icon_return));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                switch (index){
//                    case 1:
//                        FragmentManager fm = getFragmentManager();
//                        FragmentTransaction transaction = fm.beginTransaction();
//                        if(firstFragment==null){
//                            firstFragment=new AddBankFragment_first();
//                        }
//                        transaction.replace(R.id.sjt_bind_bank_fl,firstFragment);
//                        transaction.addToBackStack(null);
//                        transaction.commit();
//                        index=0;
//                        break;
//                    default:
//                        finish();
//                        break;
//
//                }
                finish();
            }
        });

        if ("0".equals(status)){
            titleBar.setTitle(getResources().getString(R.string.tab_add_quickpay_card));
        }


    }

    @Override
    protected void initEvent() {
        SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
        idCard = mainSharedPreferences.getString("idCard", "");
        name = mainSharedPreferences.getString("name", "");
        isRealName=mainSharedPreferences.getString("isRealName","");
        if (isRealName.equals("1")){
            et_username.setEnabled(false);
            et_idcard.setEnabled(false);
            et_username.setText(name);
            et_idcard.setText(idCard.substring(0, 4) + " **** **** " + idCard.substring(idCard.length() - 4, idCard.length()));
        }
        if ("0".equals(status)){
            et_bankcardno.setEnabled(false);
            et_bankcardno.setText(bankCardNo.substring(0,4)+ " **** **** " + bankCardNo.substring(bankCardNo.length() - 4, bankCardNo.length()));
        }
        btn_second.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isRealName.equals("0")){
                    idCard = et_idcard.getText().toString().trim();
                    name = et_username.getText().toString().trim();
                }
                if (et_username.getText().toString() == null || et_username.getText().toString().equals("")) {
                    TipUtil.showToast(getResources().getString(R.string.error_no_name), AddBankActivity.this, 1);
                } else if (et_idcard.getText().toString() == null || et_idcard.getText().toString().equals("")) {
                    TipUtil.showToast(getResources().getString(R.string.error_no_idcard), AddBankActivity.this, 1);
                } else if (et_bankcardno.getText().toString() == null || et_bankcardno.getText().toString().equals("")) {
                    TipUtil.showToast(getResources().getString(R.string.error_no_bankno),AddBankActivity.this, 1);
                } else if (et_bankcardno.length() < 10 || et_bankcardno.length() > 23) {
                    TipUtil.showToast(getResources().getString(R.string.error_bankcard), AddBankActivity.this, 1);
                } else {
                    if ("0".equals(status)){
                        activateSendAuthCode();
                    }else {
                        applyBindBankCard();
                    }

                }


            }
        });
    }

    @Override
    protected void initData() {
//        FragmentManager fm = getFragmentManager();
//        FragmentTransaction transaction = fm.beginTransaction();
//        if(firstFragment==null){
//            firstFragment=new AddBankFragment_first();
//        }
//        transaction.replace(R.id.sjt_bind_bank_fl,firstFragment);
//        transaction.addToBackStack(null);
//        transaction.commit();
    }
    /**
     * 申请绑定
     */
    private void applyBindBankCard() {
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getResources().getString(R.string.error_please_waitting),AddBankActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.applyBindBankCard, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        JSONObject Data=res.getJSONObject("data");
                        Log.e("data",Data.toString());
                        BankCard bankCard = new BankCard();
                        bankCard.setCardName(Data.getString("bankName"));
                        bankCard.setBankCardNo(Data.getString("bankCardNo"));
                        bankCard.setBankCode(Data.getString("bankCode"));
                        bankCard.setCardTypeName(Data.getString("cardTypeName"));
                        bankCard.setCardType(Data.getString("cardType"));
                        bankCard.setStatus("");
                        String sn = Data.getString("sn");
                        Intent intent=new Intent(AddBankActivity.this,AddBankActivitySecond.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("name",name);
                        bundle.putString("idCard",idCard);
                        bundle.putString("sn",sn);
                        bundle.putString("Type",Type);
                        bundle.putSerializable("bankCard",bankCard);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message,AddBankActivity.this, 1);
                    }

                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service),AddBankActivity.this, 1);
                }

            }

        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network),AddBankActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("bankCardNo",et_bankcardno.getText().toString().trim());
                map.put("userName",name);
                map.put("idCard",idCard);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(stringRequest);
    }

    /**
     * 快捷支付激活发送验证码
     */
    private void  activateSendAuthCode() {
        //显示Progress Dialog
//        btnGetVCode.setTextAfter("秒").setTextBefore("获取验证码").setLenght(60*1000);//设置倒计时
        TipUtil.openProgressDialog(Constant.APPLICATION_NAME,getResources().getString(R.string.error_please_waitting),AddBankActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.activateSendAuthCode, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");

                    if (code.equals("200")) {//成功
                        JSONObject Data = res.getJSONObject("data");
                        String sn = Data.getString("sn");
//
                        BankCard bankCard = new BankCard();
                        bankCard.setCardName(bankName);
                        bankCard.setBankCardNo(bankCardNo);
                        bankCard.setBankCode(bankCode);
                        bankCard.setCardTypeName(bankType);
                        bankCard.setStatus(status);
                        bankCard.setPhone(phone);
                        Intent intent=new Intent(AddBankActivity.this,AddBankActivitySecond.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("name",name);
                        bundle.putString("idCard",idCard);
                        bundle.putString("sn",sn);
                        bundle.putString("Type",Type);
                        bundle.putSerializable("bankCard",bankCard);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    } else {//失败
                        TipUtil.showToast(message,AddBankActivity.this, 1);
                    }
                } catch (JSONException ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), AddBankActivity.this, 1);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), AddBankActivity.this, 1);
                TipUtil.closeProgressDialog();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                userId = mainSharedPreferences.getString("userId", "");
//                idCard = mainSharedPreferences.getString("idCard", "");
//                name = mainSharedPreferences.getString("name", "");
                map.put("loginId", userId);
                map.put("bankCardNo", bankCardNo);
                return map;

            }

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences =getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                Log.e("cookie", cookieValue);
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(20000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mQueue.add(stringRequest);

    }




}
